<script setup>
import { ref } from "vue";
import { formatTime } from "@/utils/format";
import { updateOrderStatus, updateOrder } from "@/api/order";
import { pay } from "@/api/pay";

const visibleDrawer = ref(false);
const orderDetail = ref({});

const emit = defineEmits(["success"]);

const handleOpen = async (row) => {
  visibleDrawer.value = true;
  orderDetail.value = { ...row };
};

// 取消订单请求参数
const cancelParams = ref({
  orderId: null,
  status: 4,
});

// 修改订单信息的参数
const updateParams = ref({
  orderId: null,
  shippingAddress: "",
  receiptName: "",
  receiptPhone: "",
});

// 取消订单
const cancelOrder = async () => {
  cancelParams.value.orderId = orderDetail.value.orderId;
  const res = await updateOrderStatus(cancelParams.value);
  ElMessage({
    message: "取消成功",
    type: "success",
  });
  closeDrawer();
  emit("success");
};
// 支付
const payOrder = async () => {
  // 先修改订单信息
  updateParams.value.orderId = orderDetail.value.orderId;
  updateParams.value.shippingAddress = orderDetail.value.shippingAddress;
  updateParams.value.receiptName = orderDetail.value.receiptName;
  updateParams.value.receiptPhone = orderDetail.value.receiptPhone;
  const res = await updateOrder(updateParams.value);
  open();
};

const open = () => {
  ElMessageBox.confirm(
    `<div style="width: 400px;">
      <table style="width: 100%; border-collapse: separate; border-spacing: 8px 12px;">
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">订单编号</td>
          <td style="text-align: left;">${orderDetail.value.orderId}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">商品名称</td>
          <td style="text-align: left;">${orderDetail.value.productName}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">购买数量</td>
          <td style="text-align: left;">${orderDetail.value.quantity}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">单价</td>
          <td style="text-align: left;">¥${orderDetail.value.unitPrice}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">姓名</td>
          <td style="text-align: left;">${orderDetail.value.receiptName}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">手机号</td>
          <td style="text-align: left;">${orderDetail.value.receiptPhone}</td>
        </tr>
        <tr>
          <td style="width: 80px; text-align: right; font-weight: 500;">地址</td>
          <td style="text-align: left;">${orderDetail.value.shippingAddress}</td>
        </tr>
      </table>
    </div>`,
    "是否确认支付",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      zf();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
// 确认支付
const zf = async () => {
  try {
    const res = await pay(orderDetail.value.orderId);
    const loading = ElLoading.service({
      lock: true,
      text: "正在跳转支付页面...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    if (res && res.data) {
      // 创建临时div存放表单
      const div = document.createElement("div");
      div.innerHTML = res.data;
      document.body.appendChild(div);

      // 查找表单
      const form = div.querySelector("form");
      if (!form) {
        ElMessage.error("未找到支付表单，无法跳转");
        loading.close();
        document.body.removeChild(div);
        return false;
      }

      // 记录跳转前的时间和状态
      const jumpStartTime = Date.now();
      let isJumped = false;

      // 监听页面 visibility 变化，判断是否离开当前页面
      const handleVisibilityChange = () => {
        if (document.hidden) {
          isJumped = true;
          ElMessage.success("已跳转到支付页面");
        }
      };
      document.addEventListener("visibilitychange", handleVisibilityChange);

      // 提交表单（跳转到支付宝）
      form.submit();

      // 定时检查是否跳转成功
      setTimeout(() => {
        document.removeEventListener(
          "visibilitychange",
          handleVisibilityChange
        );
        loading.close();
        document.body.removeChild(div);

        // 判断是否跳转成功
        if (!isJumped && Date.now() - jumpStartTime > 2000) {
          ElMessage.warning("跳转可能未成功，请检查网络或重试");
          return false;
        }
        return isJumped;
      }, 2000);
    } else {
      loading.close();
      ElMessage.error("支付数据异常，无法跳转");
      return false;
    }
  } catch (error) {
    console.error("支付请求失败:", error);
    ElMessage.error("支付请求失败，请重试");
    return false;
  }
};

// 关闭抽屉
const closeDrawer = () => {
  visibleDrawer.value = false;
  orderDetail.value = {};
  cancelParams.value = { orderId: null, status: 4 };
};

defineExpose({
  handleOpen,
});
</script>

<template>
  <!-- 抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    title="订单详情"
    direction="rtl"
    size="50%"
  >
    <el-card style="max-width: 100%">
      <el-form
        :model="orderDetail"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="orderDetail.orderId" disabled />
        </el-form-item>

        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="orderDetail.productName" disabled />
        </el-form-item>

        <el-form-item label="购买数量" prop="quantity">
          <el-input v-model="orderDetail.quantity" disabled />
        </el-form-item>

        <el-form-item label="购买时单价" prop="unitPrice">
          <el-input v-model="orderDetail.unitPrice" disabled />
        </el-form-item>

        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="orderDetail.totalPrice" disabled />
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-tag v-if="orderDetail.status === 0" type="danger">待付款</el-tag>
          <el-tag v-if="orderDetail.status === 1" type="primary">待发货</el-tag>
          <el-tag v-if="orderDetail.status === 2" type="warning">待收货</el-tag>
          <el-tag v-if="orderDetail.status === 3" type="success">已确认</el-tag>
          <el-tag v-if="orderDetail.status === 4" type="info">已取消</el-tag>
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <el-input :value="formatTime(orderDetail.createTime)" disabled />
        </el-form-item>

        <el-form-item
          label="交易编号"
          prop="transactionId"
          v-if="orderDetail.status != 0 && orderDetail.status != 4"
        >
          <el-input v-model="orderDetail.transactionId" disabled />
        </el-form-item>

        <el-form-item
          label="支付时间"
          prop="paymentTime"
          v-if="orderDetail.status != 0 && orderDetail.status != 4"
        >
          <el-input :value="formatTime(orderDetail.paymentTime)" disabled />
        </el-form-item>

        <el-form-item
          label="发货时间"
          prop="deliveryTime"
          v-if="orderDetail.status != 0 && orderDetail.status != 4"
        >
          <el-input :value="formatTime(orderDetail.deliveryTime)" disabled />
        </el-form-item>

        <el-form-item
          label="收货时间"
          prop="receiptTime"
          v-if="orderDetail.status != 0 && orderDetail.status != 4"
        >
          <el-input :value="formatTime(orderDetail.receiptTime)" disabled />
        </el-form-item>

        <el-form-item label="收货人姓名" prop="receiptName">
          <el-input
            v-model="orderDetail.receiptName"
            :disabled="orderDetail.status != 0"
          />
        </el-form-item>

        <el-form-item label="收货人电话" prop="receiptPhone">
          <el-input
            v-model="orderDetail.receiptPhone"
            :disabled="orderDetail.status != 0"
          />
        </el-form-item>

        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input
            v-model="orderDetail.shippingAddress"
            :disabled="orderDetail.status != 0"
          />
        </el-form-item>
        <el-form-item v-if="orderDetail.status == 0">
          <el-button type="info" plain @click="cancelOrder">取消订单</el-button>
          <el-button type="primary" plain @click="payOrder">支付</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-drawer>
</template>
